package corejava.vol2.ch3_socket.serversocket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ThreadedEchoServer {
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(21895);
			while (true) {
				Socket incomming = serverSocket.accept();
				ThreadedEchoHandler handler = new ThreadedEchoHandler(incomming);
				Thread t = new Thread(handler);
				t.start();
			}
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}
}

class ThreadedEchoHandler implements Runnable {
	
	private Socket incomming;
	
	public ThreadedEchoHandler(Socket in) {
		incomming = in;
	}
	
	@Override
	public void run() {
		try {
			try {
				Scanner in = new Scanner(incomming.getInputStream());
				// autoflush PrintWriter
				PrintWriter out = new PrintWriter(incomming.getOutputStream(), true);
				out.println("Hello! Enter BYE to exit.");
				
				while (in.hasNextLine()) {
					String line = in.nextLine();
					out.println("ECHO: " + line);
					if (line.trim().equals("BYE")) {
						break;
					}
				}
			}
			finally {
				incomming.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
